<?php
declare (strict_types=1);

namespace app\serviceapp;

use app\model\BaseModel;
use app\model\Messages;
use think\facade\Db;

/**
 * 通知消息
 * Class MessageService
 * @package app\serviceapp
 */
class MessageService
{


    /**
     * 获取通知消息列表
     * @param array $param 参数列表
     * @return json 返回结果
     */
    public static function getMessageList($param)
    {
        $res = Messages::alias('m')->field(['id', 'user_id userId', 'title', 'content', 'send_time sendTime', 'is_read isRead'])->where('m.user_id', $param['userId'])->paginate(['page' => $param['page'], 'list_rows' => $param['pageSize']])->toArray();
        if (empty($res)) {
            return json_ok((object)array(), 0);
        }
        $list = ['total' => $res['total'], 'currentPage' => $res['current_page'], 'lastPage' => $res['last_page'], 'data' => $res['data']];
        return json_ok($list, 0);

    }

    /**
     * 读未读消息
     * @param array $param 参数列表
     * @return json 返回结果
     */
    public static function operateUnReadMessage($param)
    {
        $where = [];
        $where[0] = ['user_id', '=', $param['userId']];
        if (strpos($param['messageId'], ',') !== false) {
            $idArr = explode(',', $param['messageId']);
            $error = [];
            foreach ($idArr as $key => $v) {
                $where[1] = ['id', '=', $v];
                $record = Db::table('t_messages')->where($where)->find();
                if (!empty($record)) {
                    if ($record['is_read'] != 0) {
                        $error[] = "ID为{$v}已读";
                    }
                } else {
                    $error[] = "ID为{$v}记录不存在";
                }
            }
            if (!empty($error)) {

                $error = implode('-', $error);
                return json_error(100, "存在以下错误:{$error}");
            }

            $where[1] = ['id', 'in', $param['messageId']];
        } else {
            $where[1] = ['id', '=', $param['messageId']];
            $record = Db::table('t_messages')->where($where)->find();
            if (!empty($record)) {
                if ($record['is_read'] != 0) {
                    return json_error(100, "存在以下错误:记录为{$param['messageId']}已读");
                }
            } else {
                return json_error(100, "存在以下错误:记录为{$param['messageId']}不存在");
            }

        }

        BaseModel::beginTrans();
        try {
            Db::table('t_messages')->where($where)->update(['is_read' => 1]);
        } catch (\Exception $e) {
            BaseModel::rollbackTrans();
            return json_error(100, $e->getMessage());
        }
        BaseModel::commitTrans();
        return json_ok((object)array(), 0);
    }

    /**
     * 获取用户的消息通知数
     * @param $userId
     */
    public static function getUserMessage($userId)
    {
        if (empty($userId)) {
            return json_error(10002);
        }

        return Messages::where('user_id=:user_id', ['user_id' => $userId])->count();
    }
}
